package main

import (
	"flag"
	"github.com/go-redis/redis"
	"github.com/valyala/fasthttp"
	"github.com/mohong122/ip2region/binding/golang"
	"net/http"
	"io/ioutil"
	"fmt"
	"bytes"
	"log"
	"gitee.com/signal.pear/register"
	"github.com/buaazp/fasthttprouter"
)

var addr = flag.String("addr", ":7359", "http service address")
var port = flag.String("port", ":7359", "http service port")
//var station = flag.String("station", "122.112.197.89:7380", "station service address")
var station = flag.String("station", "122.152.200.206:7380", "station service address")

var scheduler = flag.String("scheduler", "122.152.200.206:80", "scheduler service address")

//var station = flag.String("station", "122.112.197.89:7390", "station service address")

var newline = []byte{'\n'}
var space = []byte{' '}

func signal(ctx *fasthttp.RequestCtx) {
	wsHandler(ctx)
	return
}

func push(ctx *fasthttp.RequestCtx) {
	pushHandler(ctx)
}

func status(ctx *fasthttp.RequestCtx) {
	statusHandler(ctx)
}

var wsHandler fasthttp.RequestHandler
var pushHandler fasthttp.RequestHandler
var statusHandler fasthttp.RequestHandler

func main() {
	region, err := ip2region.New("data/ip2region.db")
	if err != nil {
		log.Printf("create new region decoder err:%v", err)
	}

	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	if err != nil {
		log.Printf("create redis client err:%v", err)
		panic(err)
	}

	flag.Parse()
	resp, err := http.Get("http://myexternalip.com/raw")
	if err != nil {
		log.Println(err)
	}
	defer resp.Body.Close()
	host, _ := ioutil.ReadAll(resp.Body)
	log.Print(host)

	//p = *port
	local := fmt.Sprintf("%s%s", string(bytes.TrimSpace(bytes.Replace(host, newline, space, -1))), *port)
	log.Print(local)
	server := register.NewServer()
	//server.IpRegion = region
	server.RegionDecoder = register.NewRegionDecoder(region)
	server.RDB = rdb
	server.SetLocalHost(local)
	server.SetRemoteHost(*station)
	server.SetScheduler(*scheduler)

	router := fasthttprouter.New()
	//router.POST("/pull", pull)
	router.GET("/status", status)
	router.POST("/push", push)
	router.GET("/wss", signal)
	router.GET("/ws", signal)

	wsHandler = func(ctx *fasthttp.RequestCtx) {
		register.ServeWs(server, ctx)
	}
	pushHandler = func(ctx *fasthttp.RequestCtx) {
		register.ServerPush(server, ctx)
	}
	statusHandler = func(ctx *fasthttp.RequestCtx) {
		register.ServeStatus(server, ctx)
	}
	//pullHandler = func(ctx *fasthttp.RequestCtx) {
	//	register.ServerPull(server, ctx)
	//}

	server.Run()
	
	err = fasthttp.ListenAndServe(*addr, router.Handler)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

